package tree;

import com.alibaba.fastjson.JSON;
import com.sun.org.apache.bcel.internal.generic.FADD;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class RightSideView {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode node1 = new TreeNode(2);
        TreeNode node4 = new TreeNode(5);
        TreeNode node5 = new TreeNode(8);
        node4.right = node5;
        node1.right = node4;
        root.left = node1;

        TreeNode node2 = new TreeNode(3);
        TreeNode node3 = new TreeNode(4);
        node2.right = node3;
        root.right = node2;
        System.out.println(JSON.toJSONString(root));

        List<Integer> list = new RightSideView().rightSideView(root);
        System.out.println(JSON.toJSONString(list));
    }

    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (i == 0) {
                    result.add(node.val);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }

            }
        }
        return result;
    }


    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }
}
